//
//  EditView.swift
//  studay
//
//  Created by APPLE on 2024/12/16.
//

import SwiftUI

struct EditView: View {
    
    
    @EnvironmentObject var todo:ToDo
    @State var title = ""
    @State var duedate = Date()
    
    @State var isFavorite:Bool = false
    @State var id:Int? = nil
    
    @Environment( \.presentationMode) var presentation
    var body: some View {
        NavigationView(){
            
            Form {
                Section(header:Text("事项")){
                    TextField("事项内容",text: $title)
                    DatePicker(selection: $duedate, label: { Text("截止时间") })
                }
                Section{
                    Toggle(isOn:$isFavorite){
                        Text("收藏")
                    }
                }
                Section{
                    Button(action: {
                        if self.id == nil {
                            self.todo.add(title:self.title,duedate:self.duedate,isFavorite: self.isFavorite)
                        } else {
                            self.todo.edit(id:self.id!,singleToDo: SingleToDo(title:self.title,duedate:self.duedate,isFavorite: self.isFavorite))
                        }
                       
                        self.presentation.wrappedValue.dismiss()
                    }) {
                        Text("确认")
                    }
                    
                   
                    Button(action: {
                        self.presentation.wrappedValue.dismiss()
                    }) {
                        Text("取消")
                    }
                }
                
            }.navigationTitle(self.id == nil ? "添加" : "编辑")
        }
    }
}

#Preview {
    EditView()
}
